// pages/match/match.js
var match = require('../../utils/match');
Page({
  tijiao(){
    var that = this;
    var matchid = this.data.matchid;
    var index = this.data.category;
    var userid = this.data.userid;
    var username = this.data.username;
    var time = new Date();
    var image = null;

    wx.chooseMedia({
      count: 1,
      success(res) {
          console.log(res.tempFiles)
          var po = res.tempFiles[0].tempFilePath.lastIndexOf(".")
          var ext = res.tempFiles[0].tempFilePath.slice(po)
          wx.cloud.uploadFile({
              cloudPath: matchid+index+userid + ext,
              filePath: res.tempFiles[0].tempFilePath,
              success(res) {
                  console.log(res.fileID);
                  image = res.fileID;
                  that.setData({
                    currentImage:image
                  });
                  var database = wx.cloud.database();
                  database.collection("tb_item").add({
                    data:{
                        matchid:matchid,
                        index:index,
                        userid:userid,
                        username:username,
                        time:time,
                        image:image
                    }
                  }).then((s)=>{
                    if(s)wx.showToast({
                      title: '提交图片成功',
                    })
                    //是否已经完成了整场比赛
                   database.collection("tb_item").where({
                     matchid:that.data.matchid,
                     userid:that.data.userid
                   }).get().then((b)=>{
                     //判断用户完成的当前的比赛的分项数量是否等于比赛中的数量
                     if(b.data.length ==  that.data.imageList.length){
                       var matchid = that.data.matchid;
                       var matchname = that.data.matchname;
                       var userid = that.data.userid;
                       var username = that.data.username;
                       //寻找当前用户名次
                       database.collection("tb_final").where({
                         matchid:matchid,
                         userid:userid
                       }).get().then((c)=>{
                         var len = c.data.length;
                         var mingci = len+1;
                         //获取比赛的结束时间
                         var endTime = new Date();
                         //获取比赛的开始时间
                         database.collection("tb_match").where({
                           _id:matchid
                         }).get().then((d)=>{
                           var beginTime = d.data[0].beginTime;
                           //比赛的时间间距
                           var shijiancha = endTime.getTime()-beginTime.getTime();
                           var hours = Math.floor(shijiancha/(1000*60*60));
                           var min = Math.floor(shijiancha%(1000*60*60)/60000);
                           var sec = Math.floor(shijiancha%6000/1000);
                           var haoshi = hours+"小时"+min+"分钟"+sec+"秒钟";
                           database.collection("tb_final").add({
                             data:{
                               matchid:matchid,
                               matchname:matchname,
                               userid:userid,
                               username:username,
                               mingci:"第"+mingci+"名",
                               shijiancha:shijiancha,
                               haoshi:haoshi
                             }
                           }).then((e)=>{
                             if(e)wx.showToast({
                               title: '你已经完成了比赛，获得第'+mingci+"名",
                             });
                             //判断该用户是否为整个小队最后一个完成的人
                             database.collection("tb_rudui").where({
                               userid:that.data.userid
                             }).get().then((g)=>{
                               if(g.data.length==0)return;
                                 var groupid = g.data[0].groupid;
                                 //找到小队的人数
                                 database.collection("tb_rudui").where({
                                   groupid:groupid
                                 }).get().then((h)=>{
                                     //记录下来小队的人数
                                     var renshu = h.data.length;
                                     var groupname = h.data[0].groupname;
                                     //区寻找小队里面的人的成绩
                                     wx.cloud.callFunction({
                                         name:"get_group_final",
                                         data:{
                                           groupid:groupid
                                         },
                                         success:res=>{
                                           //数出小组中有成绩的人数
                                           var data = res.result;
                                           for(let i=0;i<data.length;i++){
                                             if(data[i].list.length>0)sum=sum+1;
                                           }
                                           //判断有成绩的人是否等于小组人数
                                           if(renshu == sum){
                                             //到小组成绩表里面查询指定比赛的记录条
                                             database.collection("tb_xiaozu_chengji").where({
                                              matchid:that.data.matchid
                                             }).get().then((x)=>{
                                               var mingci = x.data.length+1;
                                               var h = haoshi;
                                               var s = shijiancha;
                                               database.collection("tb_xiaozu_chengji").add({
                                                 data:{
                                                   matcchid:matchid,
                                                   matchname:matchname,
                                                   groupid:groupid,
                                                   groupname:groupname,
                                                   mingci:mingci,
                                                   shijiancha:s,
                                                   haoshi:h

                                                 }
                                               }).then((z)=>{
                                                if(z)wx.showToast({
                                                  title: '小组比赛完成'+mingci,
                                                })
                                               })
                                             });

                                           }
                                         },
                                         fail:err=>{

                                         }
                                     });
                                 })
                             });
                           })
                         });
                       })
                     }
                   });
                  })
              }
          })
      }
  })
  },
    click:function(e){
    this.setData({
      category:e.currentTarget.id
    });
    var that = this;
    that.setData({
     isWeiwancheng:true
    });
    var database = wx.cloud.database();
    database.collection("tb_item").where({
      userid:that.data.userid,
      matchid:that.data.matchid,
      index:that.data.category+""
    }).get().then((a)=>{
      if(a.data.length>0){
        that.setData({
          isWeiwancheng:false
        });
      }
    })
    
    database.collection("tb_item").where({
      matchid:that.data.matchid,
      index:that.data.category+""
    }).get().then((res)=>{
      that.setData({
        xuanshou:res.data
      });
      for(let i=0;i<that.data.xuanshou.length;i++){
        var time = that.data.xuanshou[i].time;
        var d = time.toLocaleDateString().substring(0,10);
        var t = time.toTimeString().substring(0,8);
        time = d+" "+t;
        that.data.xuanshou[i].time = time;
      }
      that.setData({
        xuanshou:that.data.xuanshou
      });
    })
    },
    dianji(){
      var k = this.data.category;
      var img = this.data.imageList[k];
      this.setData({
        dialogShow_match:true,
        currentImage:img
      });
    },
    /**
     * 页面的初始数据
     */
    data: {
      isWeiwancheng:true,
      xuanshou:[],
      currentImage:null,
      username:null,
      userid:null,
      matchid:null,
      matchname:null,
      picname:[],
      imageList:[],
      xuanshou:[],
      matches:match.list,
      category:0,
      id:null,
      dialogShow_match:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      var that = this;
      wx.getStorage({
        key:"userid",
        success(res){
          that.setData({
            userid:res.data
          });
          //到数据库里面找到当前用户参加的比赛
          var database = wx.cloud.database();
          database.collection("th_user").where({
            _id:that.data.userid
          }).get().then((r)=>{
            that.setData({
              username:r.data[0].name
            });
          })
          //调用云函数实现多表联合查询
          wx.cloud.callFunction({
                name:"get_current_match",
                data:{
                  userid:that.data.userid
                },
                success:res=>{
               console.log("云函数返回的数据条数:"+res.result.list.length);
               var  data = res.result.list;
               for(let i=0;i<data.length;i++){
                 var f1 = true;
                 data[i].list1[0].hasOwnProperty("beginTime");
                 if(!f1)continue;
                 var f2 = true;
                 for(let j=0;j<data[i].list2.length;j++){
                   if(data[i].matchid == data[i].list2[j].matchid){
                     f2 = false;
                     break;
                   }
                 }
                 if(!f2)continue;
                 that.setData({
                      matchid:data[i].matchid,
                      matchname:data[i].matchname
                 });
                  break;
               }
               wx.setNavigationBarTitle({
                title: that.data.matchname,
              });
              database.collection("tb_item").where({
                matchid:that.data.matchid,
                index:0+""
              }).get().then((g)=>{             
                that.setData({
                  xuanshou:g.data
                });
                //把选手数组当中的字符串内容变成可以理解的内容
                for(let i=0;i<that.data.xuanshou.length;i++){
                  var time = that.data.xuanshou[i].time;
                  var d = time.toLocaleDateString().substring(0,10);
                  var t = time.toTimeString().substring(0,8);
                  var time = d+" "+t;
                  that.data.xuanshou[i].time = time;
                }
                 that.setData({
                   xuanshou:that.data.xuanshou
                 })
              });
              database.collection("tb_match").where({
                _id:that.data.matchid
              }).get().then((m)=>{
                var imageList = m.data[0].imageList;
                var picnames = [];
                for(let i=0;i<imageList.length;i++){
                    var data = imageList[i];
                    var loc = data.lastIndexOf("/");
                    data = data.slice(loc+1);
                    loc = data.lastIndexOf(".");
                    data = data.slice(0,loc);
                    picnames.push(data);
                }
                that.setData({
                  imageList:imageList,
                  picnames:picnames
                });
                //观察指定比赛，指定分项
                database.collection("tb_item").where({
                  userid:that.data.userid,
                  matchid:that.data.matchid,
                  index:0+""
                }).get().then((a)=>{
                  if(a.data.length>0){
                    that.setData({
                      isWeiwancheng:false
                    });
                  }
                })
              });
            
                },
                fail:err=>{
                  console.log(err);
                }
          });
          
       /* database.collection("tb_baoming").aggregate().lookup({
            from:"tb_match",
            localField:"matchid",
            foreignField:"_id",
            as:"matchdetail"
          }).lookup({
            from:"tb_final",
            localField:"userid",
            foreignField:"userid",
            as:"finaldetail"
          }).match({
            userid:that.data.userid
          }).end().then((msg)=>{
            //判断该比赛必须有开始比赛时间字段而且必须该用户没有完成
              var k = -1;
              for(let i=0;i<msg.data.length;i++){
                var data = msg.data[i];
                var f1 = data.matchdetail[0].hasOwnProperty("beginTime")
                if(!f1)continue;
                var f2 = true;
                for(let j=0;j<data.finaldetail.length;j++){
                 if(data.finaldetail[j].matchid == data.matchid){
                   f2 = false;
                   break;
                 }
                }
                if(!f2)continue;
                k = i;
 
              }
              if(k==-1)return;
             that.setData({
              matchid:msg.data[k].matchid,
              matchname:msg.data[k].matchname
            });
            wx.setNavigationBarTitle({
              title: msg.data[k].matchname,
            });
            database.collection("tb_item").where({
              matchid:that.data.matchid,
              index:0+""
            }).get().then((g)=>{             
              that.setData({
                xuanshou:g.data
              });
              //把选手数组当中的字符串内容变成可以理解的内容
              for(let i=0;i<that.data.xuanshou.length;i++){
                var time = that.data.xuanshou[i].time;
                var d = time.toLocaleDateString().substring(0,10);
                var t = time.toTimeString().substring(0,8);
                var time = d+" "+t;
                that.data.xuanshou[i].time = time;
              }
               that.setData({
                 xuanshou:that.data.xuanshou
               })
            });
            database.collection("tb_match").where({
              _id:that.data.matchid
            }).get().then((m)=>{
              var imageList = m.data[0].imageList;
              var picnames = [];
              for(let i=0;i<imageList.length;i++){
                  var data = imageList[i];
                  var loc = data.lastIndexOf("/");
                  data = data.slice(loc+1);
                  loc = data.lastIndexOf(".");
                  data = data.slice(0,loc);
                  picnames.push(data);
              }
              that.setData({
                imageList:imageList,
                picnames:picnames
              });
              //观察指定比赛，指定分项
              database.collection("tb_item").where({
                userid:that.data.userid,
                matchid:that.data.matchid,
                index:0+""
              }).get().then((a)=>{
                if(a.data.length>0){
                  that.setData({
                    isWeiwancheng:false
                  });
                }
              })
            });
          })*/
        }
      })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})